<template>
  <view>
    <view class="goods-list">
      <view v-for="(item,index) in goodsList" :key="index" @click="gotoDetail(item)">
        <!-- 为 my-goods 组件动态绑定 goods 属性的值 -->
        <my-goods :goods="item"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        queryObj: {
          //接口参数名query
          query: '',
          //接口参数名cid
          cid: '',
          //每次默认查7条，因为我喜欢7
          pagesize: 8,
          //当前是第几页
          pagenum: 1
        },
        //记录接口数据总条数
        total: 0,
        //存储查询数据集合
        goodsList: [],
        // 是否正在请求数据
        isloading: false

      };
    },
    onLoad(options) {
      //接收参数转存到this.queryObj中
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      this.getGoodsList()
    },
    onPullDownRefresh() {
      // 1. 重置关键数据
      this.queryObj.pagenum = 1
      this.total = 0
      this.isloading = false
      this.goodsList = []

      // 2. 重新发起请求
      this.getGoodsList(() => uni.stopPullDownRefresh())
    },
    onReachBottom() {

      if (this.isloading) return
      if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('数据加载完毕！')
      // 让页码值自增 +1
      this.queryObj.pagenum += 1
      // 重新获取列表数据
      this.getGoodsList()
    },
    methods: {
      //发起获取商品数据请求
      async getGoodsList(cb) {
        this.isloading = true;
        const {
          data: res
        } =
        await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        // 只要数据请求完毕，就立即按需调用 cb 回调函数
        cb && cb()
        if (res.meta.status != 200) return uni.$showMsg()
        this.total = res.message.total
        this.goodsList = [...this.goodsList, ...res.message.goods]
        this.isloading = false
      },
      // 点击跳转到商品详情页面
      gotoDetail(item) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      }
    }

  }
</script>

<style lang="scss">
  .goodsList {
    padding: 10px 5px;
  }
</style>
